import hashlib
import hmac
import random
import string
import requests
import time
import jsonpath

SECRET_KEY = "DebugTalk"



def RandomEmail(rang=None,emailType=None):
    __emailtype = ["@qq.com", "@163.com", "@126.com", "@189.com"]
    # 如果没有指定邮箱类型，默认在 __emailtype中随机一个
    if emailType == None:
        __randomEmail = random.choice(__emailtype)
    else:
        __randomEmail = emailType
    # 如果没有指定邮箱长度，默认在4-10之间随机
    if rang == None:
        __rang = random.randint(4, 10)
    else:
        __rang = int(rang)
    __Number = "0123456789qbcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPWRSTUVWXYZ"
    __randomNumber = "".join(random.choice(__Number) for i in range(__rang))
    _email = __randomNumber + __randomEmail
    return _email


def sleep_N_secs( n_secs):
    """ sleep n seconds after request
    """
    time.sleep(n_secs)

def gen_random_string(str_len):
    random_char_list = []
    for _ in range(str_len):
        random_char = random.choice(string.ascii_letters + string.digits)
        random_char_list.append(random_char)

    random_string = ''.join(random_char_list)
    return random_string

def get_sign(*args):
    content = ''.join(args).encode('ascii')
    sign_key = SECRET_KEY.encode('ascii')
    sign = hmac.new(sign_key, content, hashlib.sha1).hexdigest()
    return sign

def get_token():
    try:
        # url = 'http://10.5.38.208:8080/api/auth/oauth/token'
        # url = 'http://idp.ams.bespinglobal.cn/api/auth/oauth/token'
        url = 'http://idp.ams.bespinglobal.cn/api/auth/admin/oauth/token'
        data = {"password": "e3068307ddde265eadf0a95140882b9c", "username": "autotest","plat":"manage"}
        headers = {"content-type": "application/x-www-form-urlencoded"}
        response = requests.post(url=url, data=data, headers=headers)
        token = "Bearer "+response.json()["access_token"]
    except Exception as e:
        raise Exception("获取管理员端token失败请检查!!!")
    return token

def get_user_token():
    try:
        url = 'http://idp.ams.bespinglobal.cn/api/auth/oauth/token'
        data = {"password": "e3068307ddde265eadf0a95140882b9c", "username": "autotest2"}
        headers = {"content-type": "application/x-www-form-urlencoded"}
        response = requests.post(url=url, data=data, headers=headers)
        token = "Bearer "+response.json()["access_token"]
    except Exception as e:
        raise Exception("获取用户端token失败请检查!!!")
    return token

def get_value(responseStr,jsonpath_str,expect_str,expect_value,need_str):
    """
    :param responseStr: 接口返回值
    :param jsonpath_str: 需要取值jsonapth表达式
    :param expect_str: 查找需要取的条件字段名称
    :param expect_value:需要取的预期条件字段值
    :param need_str: 需要取的目标字段名称
    :return:
    """
    searchResult = jsonpath.jsonpath(responseStr, jsonpath_str)
    assert searchResult , "返回结果中，不存在满足匹配条件：%s" % jsonpath_str
    # print(searchResult)
    #searchResult为一个list，里面内容为dict
    # try:
    #     for i in searchResult[0]:
    #         if str(i[expect_str]) == str(expect_value):
    #             return i[need_str]
    # except Exception:
    #     raise Exception("获取目标字段值失败，请检查！！！")

    for i in searchResult[0]:
        try:
            if str(i[expect_str]) == str(expect_value):
                return i[need_str]
        except KeyError as e:
            continue


def get_value_list(responseStr,jsonpath_str,expect_str,expect_value,need_str):
    """
    :param responseStr: 接口返回值
    :param jsonpath_str: 需要取值jsonapth表达式
    :param expect_str: 查找需要取的条件字段名称
    :param expect_value:需要取的预期条件字段值
    :param need_str: 需要取的目标字段名称
    :return:
    """
    searchResult = jsonpath.jsonpath(responseStr, jsonpath_str)
    assert searchResult , "返回结果中，不存在满足匹配条件：%s" % jsonpath_str
    # print(searchResult)
    #searchResult为一个list，里面内容为dict
    get_value_list = []
    for i in searchResult[0]:
        try:
            if str(i[expect_str]) == str(expect_value):
                get_value_list.append(i[need_str])
        except KeyError as e:
            continue
    return get_value_list

def get_list_yaml_value(mylist,index):
    return mylist[index]


# def get_value(data):
#     """
#     :param responseStr: 接口返回值
#     :param jsonpath_str: 需要取值jsonapth表达式
#     :param expect_str: 查找需要取的条件字段名称
#     :param expect_value:需要取的预期条件字段值
#     :param need_str: 需要取的目标字段名称
#     :return:
#     """
#     return (100+int(data))


if __name__ == '__main__':
    # url = 'http://10.5.38.208:8080/api/auth/oauth/token'
    # abobo = get_user_token()
    abobo = get_token()
    print(abobo)


    # abobo = {'success': True, 'result': {'data': [
    #     {'id': '77', 'title': '自动化测试数据(待删除)', 'link': 'http://www.baidu.com', 'type': 2, 'sort': 9999, 'item1': '2'},
    #     {'id': '42', 'title': '亿通行', 'img': '/2019-11-13-small/image/BqtGmfQvyZlEgNQY42V.jpg',
    #      'link': 'http://www.baidu.com', 'type': 3, 'sort': 100, 'item1': '2'},
    #     {'id': '55', 'title': '运营分析工具', 'img': '/2019-12-08-small/image/LlTkRi0cHqjyzk3k8Ow.',
    #      'link': 'http://idp.ams.bespinglobal.cn/', 'type': 3, 'sort': 30, 'item1': 'PRODUCT'},
    #     {'id': '26', 'title': '热点线索发现', 'img': '/2019-12-08-small/image/Rkxlbj1qM1ttnCd0DU9.',
    #      'link': 'http://idp.ams.bespinglobal.cn/', 'type': 3, 'sort': 21, 'item1': 'PRODUCT'},
    #     {'id': '71', 'title': '新加的', 'img': '/2020-05-25-small/image/RuCNy2NhZAhw9qekGHf.png', 'link': 'ffff2222',
    #      'type': 4, 'sort': 20, 'item1': '2'},
    #     {'id': '33', 'title': '云虚拟机', 'link': '', 'type': 2, 'content': '24小时极速收录包年特价促销', 'sort': 13, 'label': '测试link',
    #      'labelDisplay': True, 'item1': '58'},
    #     {'id': '38', 'title': '商务安全主机', 'link': '1', 'type': 2, 'content': '360度网站安全防护4折起', 'sort': 12, 'label': '1',
    #      'labelDisplay': True, 'item1': '199'},
    #     {'id': '41', 'title': '容器服务', 'img': '2', 'link': '/product?pcode=cluster', 'type': 1,
    #      'content': '为用户提供以多集群、多租户为核心的资源管理能力。', 'sort': 12},
    #     {'id': '28', 'title': 'CDN流量包', 'type': 2, 'content': '按流量计费直降42%', 'sort': 10, 'label': '24小时急速收录',
    #      'labelDisplay': True, 'item1': '99'},
    #     {'id': '47', 'title': '全新S6云活动', 'link': '', 'type': 2, 'content': '24小时极速收录包年特价促销', 'sort': 10,
    #      'label': '神奇的测试', 'labelDisplay': True, 'item1': '99'},
    #     {'id': '70', 'title': 'test产品', 'img': '/2020-05-25-small/image/6Is3efdOsxxl36vhV4h.png', 'link': 'nnn',
    #      'type': 3, 'sort': 10, 'item1': '2'}, {'id': '27', 'title': '云解析 DNS', 'link': '/product?pcode=DNS', 'type': 1,
    #                                             'content': '为广大用户提供稳定、安全、快速、智能的域名解析服务。', 'sort': 5},
    #     {'id': '53', 'title': '行为分析', 'img': '/2019-12-08-small/image/JSNp3Gmkwff2t4yT4J4.',
    #      'link': 'http://idp.ams.bespinglobal.cn/', 'type': 3, 'sort': 4, 'item1': 'PRODUCT'},
    #     {'id': '25', 'title': '构建云安全服务', 'img': '/2019-12-08-small/image/TADLbmSFQeBxihPGA3M.', 'type': 3,
    #      'content': '汇聚各种高品质应用，提供良好的软件服务', 'sort': 3, 'item1': 'MODULE'},
    #     {'id': '52', 'title': '智能辅助写作', 'img': '/2019-12-08-small/image/j4HYt8CdmJV6f1qvU59.',
    #      'link': 'http://idp.ams.bespinglobal.cn/', 'type': 3, 'sort': 3, 'item1': 'PRODUCT'},
    #     {'id': '60', 'title': 'test', 'img': '/2019-12-08-small/image/qUr7BepnGNusj86BDB3.',
    #      'link': 'http://www.baidu.com', 'type': 3, 'sort': 3, 'item1': '2'},
    #     {'id': '31', 'title': '高品质服务市场', 'img': '/2019-12-08-small/image/eTqHsIoxgZucmYyW9Mr.', 'type': 3,
    #      'content': '主动防御，服务器全方位自动化安全运营闭环', 'sort': 2, 'item1': 'MODULE'},
    #     {'id': '57', 'title': '传播分析', 'img': '/2019-12-08-small/image/9jBHi8eoeVtl34osqir.', 'link': 'www.baidu.com',
    #      'type': 3, 'sort': 2, 'item1': '2'},
    #     {'id': '59', 'title': '测试推荐', 'img': '/2019-12-08-small/image/ovVDVbGza2CtuVh67Wa.',
    #      'link': 'http://www.baidu.com', 'type': 3, 'sort': 2, 'item1': '2'},
    #     {'id': '43', 'title': '人物库PD', 'link': '/product?pcode=UPBA', 'type': 1,
    #      'content': '挖掘分析，公众人物库，并进行多维度人物分析，为新闻内容生产提供支撑和依据。', 'sort': 1},
    #     {'id': '56', 'title': '内容分析', 'img': '/2019-12-08-small/image/2OJmeYjdavbz2eE4hfm.', 'link': 'www.baidu.com',
    #      'type': 3, 'sort': 1, 'item1': '2'},
    #     {'id': '58', 'title': '传播分析', 'img': '/2019-12-08-small/image/4MR2i2DsXBWReZuwtRb.', 'link': 'www.baidu.com',
    #      'type': 3, 'sort': 1, 'item1': '2'},
    #     {'id': '62', 'title': '大数据CDH节点', 'link': 'http://idp.ams.bespinglobal.cn/product?pcode=cdhNode', 'type': 3,
    #      'sort': 0, 'item1': '1'},
    #     {'id': '65', 'title': '虚拟机', 'link': 'http://idp.ams.bespinglobal.cn/product?pcode=vm', 'type': 3, 'sort': 0,
    #      'item1': '4'},
    #     {'id': '68', 'title': '弹性伸缩', 'link': 'http://idp.ams.bespinglobal.cn/product?pcode=scaling', 'type': 4,
    #      'sort': 0},
    #     {'id': '69', 'title': '容器服务 Container - 节点', 'img': '/2020-05-25-small/image/J4wNNtqKgf5jX56yyjj.png',
    #      'link': 'http://idp.ams.bespinglobal.cn/product?pcode=clusterNode', 'type': 4, 'sort': 0},
    #     {'id': '74', 'title': '云版数据库SQL Server', 'link': '/product?pcode=dbSqlServer', 'type': 3, 'sort': 0},
    #     {'id': '75', 'title': 'test', 'link': '1', 'type': 3, 'sort': 0, 'item1': 'PRODUCT'}],
    #                              'page': {'size': 100, 'totalElements': '28', 'totalPages': 1, 'number': 0}}}
    # gaga = get_value(abobo, '$.result.data','title','自动化测试数据(待删除)','id')
    # print(gaga)
    # pass